//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.restaurant.application.util;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.nebutown.base.data.View;
import com.nebutown.commonunits.dataface.definitions.FieldValue;
import com.nebutown.commonunits.dataface.definitions.PageInfo;
import com.nebutown.commonunits.utils.DateTimeUtils;
import com.nebutown.commonunits.utils.ExcelHandler;
import com.nebutown.commonunits.utils.GenerateIdUtils;
import com.nebutown.commonunits.utils.ExcelHandler.RowType;
import com.nebutown.commonunits.utils.ExcelHandler.WorkbookVersion;
import com.nebutown.description.data.OrderByColumn;
import com.nebutown.description.data.SortSpec;
import com.nebutown.generation.PickableBean;
import com.nebutown.generation.basictype.UID;
import com.nebutown.supporthome.AbstractImpl;
import com.nebutown.supporthome.CmdCapsule;
import com.restaurant.application.indexes.bookingsetlist.AssistBookingSetList;
import com.restaurant.application.level.Level;
import com.restaurant.application.levelset.LevelSet;
import com.restaurant.application.minifacade.data.BookingBO;
import com.restaurant.application.minifacade.data.BookingTime;
import com.restaurant.application.minifacade.data.ShopBO;
import com.restaurant.application.minifacade.data.ShopBookingTime;
import com.restaurant.application.reservation.support.BookingListData;
import com.restaurant.application.shop.support.ShopVo;
import com.restaurant.application.shoplist.ShopList;
import com.restaurant.application.util.counter.Counter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CommonUtils {
    private static final Logger LOG = LoggerFactory.getLogger(CommonUtils.class);
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public CommonUtils() {
    }

    public static View resultView(AbstractImpl impl, String message, PickableBean param) {
        ResultBean<PickableBean> resultBean = new ResultBean();
        resultBean.setMessage(message);
        resultBean.setData(param);
        return impl.dataOnly(impl.getClass().getName(), resultBean);
    }

    public static String likeCheck(String param) {
        param = processWords(param);
        return "%" + param + "%";
    }

    public static String processWords(String param) {
        if (Strings.isNullOrEmpty(param)) {
            return "";
        } else if (Objects.equals("null", param)) {
            return "";
        } else {
            if (param.contains("'")) {
                param = param.replace("'", "");
            }

            if (param.contains("\"")) {
                param = param.replace("\"", "");
            }

            return param;
        }
    }

    public static String equalsCheck(String param) {
        return processWords(param);
    }

    public static String getCurrentDate(int i) {
        LocalDate localDate = LocalDate.now(ZoneId.of("UTC+8"));
        StringBuilder s = new StringBuilder();
        String dateYear = String.valueOf(localDate.getYear());
        String year = dateYear.substring(dateYear.length() - i);
        String month = String.format("%02d", localDate.getMonthValue());
        String day = String.format("%02d", localDate.getDayOfMonth());
        return s.append(year).append(month).append(day).toString();
    }

    public static SortSpec getSort() {
        return getSort((String)null);
    }

    public static SortSpec getSort(String columnName) {
        if (Strings.isNullOrEmpty(columnName)) {
            columnName = "MODIFYTIME";
        }

        return (new SortSpec()).addColumns((new OrderByColumn()).withColumnName(columnName).withAscending(false));
    }

    public static List<List<String>> getExcel(InputStream inputStream) {
        List<List<String>> read = new ArrayList();
        ExcelHandler excelHandler = null;

        try {
            if (inputStream != null) {
                excelHandler = new ExcelHandler(inputStream, WorkbookVersion.XLSX);
            }
        } catch (IOException var4) {
            var4.printStackTrace();
        }

        if (excelHandler != null) {
            read = excelHandler.read();
            excelHandler.close();
        }

        return (List)read;
    }

    public static File getFile(List<List<String>> data, String fileName, String fileType, String sheetName) throws IOException {
        LinkedHashMap<String, List<List<String>>> hashMap = new LinkedHashMap();
        hashMap.put(sheetName, data);
        return getMultiSheetFile(hashMap, fileName, fileType);
    }

    public static File getMultiSheetFile(Map<String, List<List<String>>> map, String fileName, String fileType) throws IOException {
        ExcelHandler excelHandler = new ExcelHandler(WorkbookVersion.XLSX);
        map.forEach((k, v) -> {
            excelHandler.createSheet();
        });
        AtomicInteger m = new AtomicInteger(0);
        map.forEach((k, v) -> {
            int i = m.getAndIncrement();
            excelHandler.setSheetName(i, k);
            excelHandler.write(i, v, true);
        });
        excelHandler.setRowStyle(0, 0, excelHandler.makeStyle(RowType.HEADER));
        File file = File.createTempFile(fileName, fileType);
        FileOutputStream ops = new FileOutputStream(file);
        excelHandler.getWorkbook().write(ops);
        ops.flush();
        ops.close();
        excelHandler.close();
        return file;
    }

    public static long getTodayZeroMills() {
        return LocalDateTime.of(LocalDate.now(), LocalTime.MIN).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    public static long getTodayMaxMills() {
        return LocalDateTime.of(LocalDate.now(), LocalTime.MAX).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    public static long dateTimeToLong(String date) {
        LocalDate parse = LocalDate.parse(date);
        return parse.atStartOfDay(ZoneId.of("+8")).toInstant().toEpochMilli();
    }

    public static String longToTimeString(long date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneId.of("+8"));
        LocalDate localDate = LocalDate.of(localDateTime.getYear(), localDateTime.getMonth(), localDateTime.getDayOfMonth());
        return localDate.format(DateTimeFormatter.ISO_DATE);
    }

    public static String castTime(long time) {
        return LocalTime.ofSecondOfDay(time / 1000L).format(DateTimeFormatter.ISO_LOCAL_TIME);
    }

    public static long reverseTime(String time) {
        return (long)LocalTime.parse(time, DateTimeFormatter.ISO_LOCAL_TIME).toSecondOfDay() * 1000L;
    }

    public static String erCodeGenerate(String content) {
        LOG.debug(" ========erCode content========{}", content);
        byte[] bytes = ErCodeGen.generateQRcodeByte(content, 300, "jpg");
        String domainAndKey = WeChatCode.uploadFilesViaServer(bytes);
        LOG.info("getCode ========= 域名+Key：{} ========= ", domainAndKey);
        if (!Strings.isNullOrEmpty(domainAndKey)) {
            String[] dKeyArray = domainAndKey.split(",");
            return dKeyArray.length > 1 ? "https://" + dKeyArray[0] + "/" + dKeyArray[1] : null;
        } else {
            LOG.info(" ======== 二维码生成错误，请稍后重试！========");
            return "";
        }
    }

    public static String getDate() {
        return LocalDateTime.now(ZoneId.of("UTC+8")).format(DATETIME_FORMATTER);
    }

    public static void sendPhoneCode(AbstractImpl impl, String phoneNumber, String sessionKey) {
        String code = GenerateIdUtils.getRandomCode();
        BoxPhoneCodeUtils.sendVerificationCode(phoneNumber, code);
        impl.addToSessionCache(sessionKey, code);
    }

    public static List<String> getLevelNameList(AbstractImpl impl) {
        List<UID> levelUidList = ((LevelSet)impl.getSingleton(LevelSet.class)).findAllLevel();
        List<String> levelName = Lists.newArrayList();
        if (levelUidList.size() > 0) {
            levelUidList.forEach((e) -> {
                levelName.add(((Level)impl.getUnit(Level.class, e)).findData().getMemberName());
            });
        }

        return levelName;
    }

    public static UID getCustomerUidBySession(AbstractImpl impl) {
        return impl.getGate();
    }

    public static String getCustomerNumber(String type, String channel, long count) {
        String countStr;
        if (count <= Constant.LENGTH_FIVE) {
            countStr = String.format("%06d", count);
        } else {
            countStr = String.valueOf(count);
        }

        return type + channel + countStr;
    }

    public static String getReservationNumber(String strStart, long count) {
        String countStr;
        if (count < 10L) {
            countStr = String.format("%02d", count);
        } else {
            countStr = String.valueOf(count);
        }

        return strStart + countStr;
    }

    public static List<String> getAllShopName(AbstractImpl impl) {
        List<ShopVo> shopVoList = ((ShopList)impl.getSingleton(ShopList.class)).findAllShopData();
        List<String> shopNameList = Lists.newArrayList();
        if (shopVoList.size() > 0) {
            shopVoList.forEach((e) -> {
                shopNameList.add(e.getName());
            });
        }

        return shopNameList;
    }

    public static String getGoodsNumber(AbstractImpl impl) {
        Integer count = ((Counter)impl.getSingleton(Counter.class)).get("goodsNumber");
        String number = String.format("%03d", count);
        String time = DateTimeUtils.getDateTimeFarmatStrAndTime(DateTimeUtils.getCurrentMillisecond(), "yyyyMMdd");
        return "P" + time + number;
    }

    public static String getOderNumber(AbstractImpl impl) {
        Integer count = ((Counter)impl.getSingleton(Counter.class)).get("orderNumber");
        String number = String.format("%02d", count);
        String time = DateTimeUtils.getDateTimeFarmatStrAndTime(DateTimeUtils.getCurrentMillisecond(), "yyyyMMdd");
        return "J" + time + number;
    }

    public static String removeNullStr(String s) {
        return Strings.isNullOrEmpty(s) ? "" : s;
    }

    public static String getNullStr(String s) {
        return Strings.isNullOrEmpty(s) ? null : s;
    }

    public static PageInfo getPageInfo(int currentPage, int pageSize, int totalRecord, AbstractImpl impl, CmdCapsule cmd, String pageFiled) {
        return new PageInfo(pageSize, currentPage, (totalRecord + pageSize - 1) / pageSize, totalRecord, impl.getPath(cmd, new int[0]), pageFiled);
    }

    public static FieldValue getSimpleCell(PickableBean bean, String field) {
        return (new FieldValue()).withValue(String.valueOf(bean.getValueOf(field)));
    }

    public static BookingListData getBooking(String shopId, String service, AbstractImpl impl) {
        BookingListData listData = new BookingListData();
        List<String> services = Lists.newArrayList();
        List<String> shopNameList = Lists.newArrayList();
        List<String> dateList = Lists.newArrayList();
        List<String> timeList = Lists.newArrayList();
        BookingBO bookingBO = ((AssistBookingSetList)impl.getSingleton(AssistBookingSetList.class)).findBookingShops();
        if (Objects.nonNull(bookingBO) && bookingBO.getService().size() > 0) {
            services = bookingBO.getService();
            shopNameList = (List)bookingBO.getShops().stream().map(ShopBO::getShopName).collect(Collectors.toList());
        }

        if (!Strings.isNullOrEmpty(shopId)) {
            ShopBookingTime shopBookingTime;
            if (!Strings.isNullOrEmpty(service)) {
                shopBookingTime = ((AssistBookingSetList)impl.getSingleton(AssistBookingSetList.class)).findBookingSetList(shopId, service);
                if (Objects.nonNull(shopBookingTime)) {
                    if (shopBookingTime.getServices().size() > 0) {
                        services = shopBookingTime.getServices();
                    }

                    if (shopBookingTime.getBookingTime().size() > 0) {
                        dateList = (List)shopBookingTime.getBookingTime().stream().map(BookingTime::getDate).collect(Collectors.toList());
                        if (((BookingTime)shopBookingTime.getBookingTime().get(0)).getTime().size() > 0) {
                            timeList = ((BookingTime)shopBookingTime.getBookingTime().get(0)).getTime();
                        }
                    }
                }
            } else {
                shopBookingTime = ((AssistBookingSetList)impl.getSingleton(AssistBookingSetList.class)).findBookingSetList(shopId, (String)null);
                if (Objects.nonNull(shopBookingTime) && shopBookingTime.getServices().size() > 0) {
                    services = shopBookingTime.getServices();
                }
            }
        } else if (!Strings.isNullOrEmpty(service)) {
            List<ShopBookingTime> bookingTimes = ((AssistBookingSetList)impl.getSingleton(AssistBookingSetList.class)).findBookingSetListByService(service);
            if (bookingTimes.size() > 0) {
                shopNameList = (List)bookingTimes.stream().map(ShopBookingTime::getShopName).collect(Collectors.toList());
            }
        }

        return listData.withServices((List)services).withShopNameList((List)shopNameList).withDateList((List)dateList).withTimeList((List)timeList);
    }

    public static String listToString(List<String> strList) {
        return Objects.nonNull(strList) && strList.size() > 0 ? String.join(",", strList) : null;
    }
}
